<template>
	<div class="ebook" ref="ebook">
		<!-- 电子书页眉组件 -->
		<ebook-header></ebook-header>
		<!-- 阅读器标题组件 -->
		<ebook-title></ebook-title>
		<!-- 阅读器组件 -->
		<ebook-reader></ebook-reader>
		<!-- 阅读器菜单组件 -->
		<ebook-menu></ebook-menu>
		<!-- 阅读器书签组件 -->
		<ebook-bookmark></ebook-bookmark>
		<!-- 电子书页脚组件 -->
		<ebook-footer></ebook-footer>
	</div>
</template>

<script>
import EbookReader from '../../components/ebook/EbookReader'
import EbookTitle from '../../components/ebook/EbookTitle'
import EbookMenu from '../../components/ebook/EbookMenu'
import { getReadTime, saveReadTime } from '../../utils/localStorage'
import EbookBookmark from '../../components/ebook/EbookBookmark'
import EbookHeader from '../../components/ebook/EbookHeader'
import EbookFooter from '../../components/ebook/EbookFooter'
import { ebookMixin } from '../../utils/mixin'
export default {
	mixins: [ebookMixin],
	components: {
		EbookReader,
		EbookTitle,
		EbookMenu,
		EbookBookmark,
		EbookHeader,
		EbookFooter
	},  
	watch: {
		offsetY(v) { // 监听Y轴偏移量的改变
			if (!this.menuVisible && this.bookAvailable) {
				if (v > 0) {
					this.move(v)
				} else if (v === 0) { // 松开后回弹
					this.restore()
				}
			}
		}
	},
	methods: {
		restore() {
			this.$refs.ebook.style.top = 0
			this.$refs.ebook.style.transition = 'all .2s linear'
			setTimeout(() => {
				// 回弹完成后，清除动画
				this.$refs.ebook.style.transition = ''
			}, 200)
		},
		move(v) {
			this.$refs.ebook.style.top = v + 'px'
		},
		startLoopReadTime() {
			// 获取阅读时间
			let readTime = getReadTime(this.fileName)
			if (!readTime) {
				readTime = 0
			}
			this.task = setInterval(() => {
				// 每隔一秒钟记录阅读时间
				readTime++
				if (readTime % 30 === 0) { // 每隔20秒写入localStorage中
					saveReadTime(this.fileName, readTime)
				}
			}, 1000)
		}
	},
	mounted() {
		this.startLoopReadTime()
	},
	beforeDestroy() {
		if (this.task) {
			clearInterval(this.task)
		}
	}
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
	@import "../../assets/styles/global.scss";
	// @import url("../../assets/styles/global.scss");
	.ebook {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
</style>
